package com.its.common.kafka.config;

import lombok.Data;
import org.apache.kafka.clients.CommonClientConfigs;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.config.SaslConfigs;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.util.StringUtils;

import java.util.Properties;

@Data
@ConfigurationProperties(prefix = "its.kafka.producer.conf")
public class KafkaProducerProperties {

    private String bootstrapServers;

    private String acksConfig;

    private String securityProtocol; // "SASL_PLAINTEXT"

    private String mechanism; // "SCRAM-SHA-256"

    private String username;

    private String password;

//    private String partitionerClass; //自定义分区规则


    public Properties buildProperties(){
        Properties properties = new Properties();
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, this.getBootstrapServers());
        properties.put(ProducerConfig.ACKS_CONFIG, this.getAcksConfig());
        properties.put(ProducerConfig.RETRIES_CONFIG,"0");
        properties.put(ProducerConfig.BATCH_SIZE_CONFIG,"16384");
        properties.put(ProducerConfig.LINGER_MS_CONFIG,"1");
        properties.put(ProducerConfig.BUFFER_MEMORY_CONFIG,"33554432");
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
//        properties.put(ProducerConfig.PARTITIONER_CLASS_CONFIG,"com.imooc.jiangzh.kafka.producer.SamplePartition");

        if(StringUtils.hasText(this.getSecurityProtocol()) && this.getSecurityProtocol().length() > 5) {
//            properties.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SASL_PLAINTEXT");
//            properties.put(SaslConfigs.SASL_MECHANISM, "SCRAM-SHA-256");

            properties.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, this.getSecurityProtocol());
            properties.put(SaslConfigs.SASL_MECHANISM, this.getMechanism());

            if(StringUtils.hasText(this.getUsername())){
                properties.put(SaslConfigs.SASL_JAAS_CONFIG,
                        "org.apache.kafka.common.security.scram.ScramLoginModule required "
                                + "username=\"" + this.getUsername() + "\" "
                                + "password=\"" + this.getPassword() +"\";");
            }else{
                throw new RuntimeException("当前Kafka的安全协议设置为：SASL_PLAINTEXT，但没有设置用户信息");
            }
        }

        return properties;
    }
}
